#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import os.path
from typing import List, Optional, Union

from email_validator import EmailNotValidError, validate_email
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, BackgroundTasks
from sqlalchemy import func
from sqlalchemy.orm import Session

from backend.app.common.log import log
from backend.app.core.path_conf import ImgPath
from backend.app.crud import article_crud, carousel_crud, category_crud, comment_crud, friend_crud, \
    head_announcement_crud, main_announcement_crud, pay_crud, picture_crud, tag_crud, user_crud
from backend.app.datebase.db import get_db
from backend.app.model import About, Article, Subscription, WebConf
from backend.app.schema import Response200, Response403, Response404, Response500
from backend.app.schema.about import CreatAbout, UpdateAbout
from backend.app.schema.article import CreateArticle, UpdateArticle
from backend.app.schema.category import CreateCategory
from backend.app.schema.friend import CreateFriend, UpdateFriend
from backend.app.schema.head_announcement import HeadAnnounceBase
from backend.app.schema.mian_announcement import MainAnnounceBase
from backend.app.schema.tag import TagBase
from backend.app.services import jwt_security
from backend.app.services.send_email_subscription import send_email_subscription

su = APIRouter(dependencies=[Depends(jwt_security.get_current_is_superuser)])

"""
说明：管理员
"""


@su.post('/about', summary='新增关于')
async def create_about(post: CreatAbout, db: Session = Depends(get_db)):
    if db.query(func.count(About.id)).scalar() > 0:
        return HTTPException(status_code=403, detail='关于内容已存在，仅能添加一条')
    about_obj = About(about_contents=post.about_contents)
    db.add(about_obj)
    db.commit()
    db.refresh(about_obj)
    return {'code': 200, 'msg': "新增关于信息成功", 'about_contents': post.about_contents}


@su.put('/about', summary='更新关于', response_model=Union[Response200, Response500])
async def update_about(put: UpdateAbout, db: Session = Depends(get_db)):
    if db.query(func.count(About.id)).scalar() != 1:
        return Response500(msg='更新关于失败，你还没有添加关于，添加后才可以进行更新操作')
    db.query(About).update({'about_contents': put.about_contents})
    db.commit()
    return Response200(msg='更新关于内容成功', data={'put': put.about_contents})


@su.delete('/about', summary='删除关于', response_model=Union[Response200, Response500])
async def delete_about(db: Session = Depends(get_db)):
    if db.query(func.count(About.id)).scalar() != 1:
        return Response500(msg='删除关于失败，你还没有添加关于，添加后才可以进行删除操作')
    db.query(About).delete()
    db.commit()
    return Response200(msg='删除关于内容成功')


@su.post('/announcement', summary='新增头部公告', response_model=Union[Response200, Response500])
async def create_announcement(post: HeadAnnounceBase, db: Session = Depends(get_db)):
    if head_announcement_crud.get_am(db):
        head_announcement_crud.create_am(db, post)
        return Response200(msg='新增公告成功', data=post)
    return Response500(msg='新增公告失败')


@su.put('/announcement/{am_id}', summary='更新头部公告', response_model=Union[Response200, Response404, Response500])
async def update_announcement(am_id: int, put: HeadAnnounceBase, db: Session = Depends(get_db)):
    if head_announcement_crud.get_am_by_id(db, am_id):
        if head_announcement_crud.update_am(db, am_id, put):
            return Response200(msg='更新公告成功', data={
                'head_announcement': put.head_announcement,
            })
        return Response500(msg='更新公告失败, 公告id不存在或错误')
    return Response404(msg='公告不存在，请重新输入')


@su.delete('/announcement/{am_id}', summary='删除头部公告', response_model=Union[Response200, Response404, Response500])
async def delete_announcement(am_id: int, db: Session = Depends(get_db)):
    if head_announcement_crud.get_am_by_id(db, am_id):
        if not head_announcement_crud.delete_am(db, am_id):
            return Response200(msg='删除公告成功')
        return Response500(msg='删除公告失败')
    return Response404(msg='公告不存在，请重新输入')


@su.post('/main_announcement', summary='新增主公告', response_model=Union[Response200, Response500])
async def create_main_announcement(post: MainAnnounceBase, db: Session = Depends(get_db)):
    if main_announcement_crud.get_am(db):
        main_announcement_crud.create_am(db, post)
        return Response200(msg='新增公告成功', data=post)
    return Response500(msg='新增公告失败')


@su.put('/main_announcement/{am_id}', summary='更新主公告', response_model=Union[Response200, Response404, Response500])
async def update_main_announcement(am_id: int, put: MainAnnounceBase, db: Session = Depends(get_db)):
    if main_announcement_crud.get_am_by_id(db, am_id):
        if main_announcement_crud.update_am(db, am_id, put):
            return Response200(msg='更新公告成功', data={
                'main_announcement': put.main_announcement
            })
        return Response500(msg='更新公告失败, 公告id不存在或错误')
    return Response404(msg='公告不存在，请重新输入')


@su.delete('/main_announcement/{am_id}', summary='删除主公告', response_model=Union[Response200, Response404, Response500])
async def delete_main_announcement(am_id: int, db: Session = Depends(get_db)):
    if main_announcement_crud.get_am_by_id(db, am_id):
        if not main_announcement_crud.delete_am(db, am_id):
            return Response200(msg='删除公告成功')
        return Response500(msg='删除公告失败')
    return Response404(msg='公告不存在，请重新输入')


@su.post('/article', summary='新增文章', response_model=Union[Response200, Response500, Response404])
async def create_detail(category_id: int, user_id: int, post: CreateArticle, request: Request, tasks: BackgroundTasks,
                        tag_id: List[int] = Query(...), db: Session = Depends(get_db)):
    if article_crud.get_article(db):
        if category_crud.get_category_by_id(db, category_id):
            if user_crud.get_user_by_id(db, user_id):
                try:
                    for tags in tag_id:
                        if not tag_crud.get_tag_by_id(db, tags):
                            raise
                except Exception:
                    raise HTTPException(status_code=404, detail='标签不存在，请检查')
                try:
                    article_crud.create_article(db, category_id, user_id, post, tag_id)
                except Exception:
                    raise HTTPException(status_code=500, detail='新增文章失败，内部错误')
                else:
                    try:
                        emails = list(db.query(Subscription.email).all())
                        article_url = (str(request.base_url) + 'v1/article/' + str(
                            db.query(Article).order_by(Article.date_time.desc()).first().id))
                        if emails is not None:
                            tasks.add_task(send_email_subscription, emails, post.title, article_url)
                    except Exception as e:
                        log.error(f'邮箱订阅发送失败!{e}')
                    finally:
                        return Response200(msg='新增文章成功', data=post)
            return Response404(msg='新增文章失败，用户不存在')
        return Response404(msg='新增文章失败，分类不存在')
    return Response500(msg='新增文章失败，内部错误')


@su.put('/article/{article_id}', summary='更新文章', response_model=Union[Response200, Response404, Response404])
async def update_detail(article_id: int, category_id: int, user_id: int, put: UpdateArticle,
                        tag_id: List[int] = Query(...), db: Session = Depends(get_db)):
    article = article_crud.get_article_by_id(db, article_id)
    if article:
        if category_crud.get_category_by_id(db, category_id):
            if user_crud.get_user_by_id(db, user_id):
                try:
                    for tags in tag_id:
                        if not tag_crud.get_tag_by_id(db, tags):
                            raise
                except Exception:
                    raise HTTPException(status_code=404, detail='标签不存在，请检查')
                if article_crud.update_article(db, article_id, category_id, user_id, put, tag_id):
                    return Response200(msg='更新文章成功', data=put)
                return Response500(msg='更新文章失败')
            return Response404(msg='更新文章失败，用户不存在')
        return Response404(msg='更新文章失败，分类不存在')
    return Response404(msg='文章不存在，请重新输入')


@su.delete('/article/{article_id}', summary='删除文章', response_model=Union[Response200, Response404, Response404])
async def delete_detail(article_id: int, db: Session = Depends(get_db)):
    if article_crud.get_article_by_id(db, article_id):
        if not article_crud.delete_article(db, article_id):
            return Response200(msg='删除文章成功')
        return Response500(msg='删除文章失败')
    return Response404(msg='文章不存在，请重新输入')


@su.post('/carousel', summary='新增轮播图', response_model=Union[Response200, Response404])
async def create_carousel(carousel: UploadFile = File(...),
                          carousel_explanation: Optional[str] = None,
                          img_title: Optional[str] = None,
                          img_alt: Optional[str] = None,
                          db: Session = Depends(get_db)):
    if carousel_crud.get_carousel(db):
        f = await carousel.read()
        if 'image' not in carousel.content_type:
            raise HTTPException(status_code=403, detail='图片格式错误，请重新选择图片')
        filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S.%f')) + '_' + carousel.filename
        with open(ImgPath + f'{filename}', 'wb') as ff:
            ff.write(f)
        carousel_crud.create_carousel(db, filename, carousel_explanation, img_title, img_alt)
        return Response200(msg='新增轮播图成功', data={
            'carousel': filename,
            'carousel_explanation': carousel_explanation,
            'img_title': img_title,
            'img_alt': img_alt})
    Response500(msg='新增轮播图失败')


@su.put('/carousel/{carousel_id}', summary='更新轮播图', response_model=Union[Response200, Response404, Response404])
async def update_carousel(carousel_id: int,
                          carousel: UploadFile = File(...),
                          carousel_explanation: Optional[str] = None,
                          img_title: Optional[str] = None,
                          img_alt: Optional[str] = None,
                          db: Session = Depends(get_db)):
    if carousel_crud.get_carousel_by_id(db, carousel_id):
        current_filename = carousel_crud.get_carousel_text(db, carousel_id)
        try:
            os.remove(ImgPath + current_filename)
        except FileExistsError:
            log.warning(f'删除图片:{current_filename}失败，未在本地找到相关图片')
        finally:
            f = await carousel.read()
            if 'image' not in carousel.content_type:
                raise HTTPException(status_code=403, detail='图片格式错误，请重新选择图片')
            filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S.%f')) + '_' + carousel.filename
            with open(ImgPath + f'{filename}', 'wb') as ff:
                ff.write(f)
        if carousel_crud.update_carousel(db, carousel_id, filename, carousel_explanation, img_title, img_alt):
            return Response200(msg='更新轮播图成功', data={
                'carousel': filename,
                'carousel_explanation': carousel_explanation,
                'img_title': img_title,
                'img_alt': img_alt,
            })
        return Response500(msg='更新轮播图失败')
    return Response404(msg='轮播图不存在，请重新输入')


@su.delete('/carousel/{carousel_id}', summary='删除轮播图', response_model=Union[Response200, Response404, Response404])
async def delete_carousel(carousel_id: int, db: Session = Depends(get_db)):
    if carousel_crud.get_carousel_by_id(db, carousel_id):
        current_filename = carousel_crud.get_carousel_text(db, carousel_id)
        try:
            os.remove(ImgPath + current_filename)
        except FileExistsError:
            log.warning(f'删除图片:{current_filename}失败，未在本地找到相关图片')
        finally:
            if not carousel_crud.delete_carousel(db, carousel_id):
                return Response200(msg='删除轮播图成功')
        return Response500(msg='删除轮播图失败')
    return Response404(msg='轮播图不存在，请重新输入')


@su.post('/category', summary='新增类型', response_model=Union[Response200, Response500, Response403])
async def create_category(post: CreateCategory, db: Session = Depends(get_db)):
    if category_crud.get_category(db):
        if not category_crud.get_category_by_name(db, post.name):
            category_crud.create_category(db, post)
            return Response200(msg='新增类型成功', data=post)
        return Response500(msg='该类型已存在，不能重复添加')
    return Response500(msg='新增类型失败')


@su.put('/category/{category_id}', summary='更新类型', response_model=Union[Response200, Response404, Response500])
async def update_category(category_id: int, put: CreateCategory, db: Session = Depends(get_db)):
    if category_crud.get_category_by_id(db, category_id):
        if not category_crud.get_category_by_name(db, put.name):
            if category_crud.update_category(db, category_id, put):
                return Response200(msg='更新类型成功', data=put)
            return Response500(msg='更新类型失败')
        return Response403(msg='该类型已存在')
    return Response404(msg='类型不存在，请重新输入')


@su.delete('/category/{category_id}', summary='删除类型', response_model=Union[Response200, Response404, Response500])
async def delete_category(category_id: int, db: Session = Depends(get_db)):
    if category_crud.get_category_by_id(db, category_id):
        if not category_crud.delete_category(db, category_id):
            return Response200(msg='删除类型成功')
        return Response500(msg='删除类型失败')
    return Response404(msg='类型不存在，请重新输入')


@su.post('/friend', summary='新增友链', response_model=Union[Response200, Response500])
async def create_friend(post: CreateFriend, db: Session = Depends(get_db)):
    if friend_crud.get_friend(db):
        friend_crud.create_friend(db, post)
        return Response200(msg='添加友链成功', deta=post)
    return Response500(msg='添加友链失败')


@su.put('/friend/{friend_id}', summary='更新友链', response_model=Union[Response200, Response404, Response500])
async def update_friend(friend_id: int, update: UpdateFriend, db: Session = Depends(get_db)):
    if friend_crud.get_friend_by_id(db, friend_id):
        if friend_crud.update_friend(db, friend_id, update):
            return Response200(msg='更新友链成功', data=update)
        return Response500(msg='更新友链失败')
    return Response404(msg='友链不存在，请重新输入')


@su.delete('/friend/{friend_id}', summary='删除友链', response_model=Union[Response200, Response404, Response500])
async def delete_friend(friend_id: int, db: Session = Depends(get_db)):
    if friend_crud.get_friend_by_id(db, friend_id):
        if not friend_crud.delete_friend(db, friend_id):
            return Response200(msg='删除友链成功')
        return Response500(msg='删除友链失败')
    return Response404(msg='友链不存在，请重新输入')


@su.post('/pay', summary='新增打赏图', response_model=Union[Response200, Response500])
async def create_pay(file: UploadFile = File(...), db: Session = Depends(get_db)):
    if pay_crud.get_pay(db):
        f = await file.read()
        if 'image' not in file.content_type:
            raise HTTPException(status_code=403, detail='图片格式错误，请重新选择图片')
        filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S.%f')) + '_' + file.filename
        with open(ImgPath + f'{filename}', 'wb') as ff:
            ff.write(f)
        pay_crud.create_pay(db, filename)
        return Response200(msg='新增打赏图成功', data={'pay_img': filename})
    return Response500(msg='新增打赏图失败')


@su.put('/pay/{pay_id}', summary='更新打赏图', response_model=Union[Response200, Response404, Response500])
async def create_pay(pay_id: int, file: UploadFile = File(...), db: Session = Depends(get_db)):
    if pay_crud.get_pay_by_id(db, pay_id):
        current_filename = pay_crud.get_pay_img_by_id(db, pay_id)
        try:
            os.remove(ImgPath + current_filename)
        except FileExistsError:
            log.warning(f'删除图片:{current_filename}失败，未在本地找到相关图片')
        finally:
            f = await file.read()
            if 'image' not in file.content_type:
                raise HTTPException(status_code=403, detail='图片格式错误，请重新选择图片')
            filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S.%f')) + '_' + file.filename
            with open(ImgPath + f'{filename}', 'wb') as ff:
                ff.write(f)
        if pay_crud.update_pay(db, pay_id, filename):
            return Response200(msg='更新打赏图成功', data={'pay_img': filename})
        return Response500(msg='更新打赏图失败')
    return Response404(msg='打赏图不存在，请重新输入')


@su.delete('/pay/{pay_id}', summary='删除打赏图', response_model=Union[Response200, Response404, Response500])
async def create_pay(pay_id: int, db: Session = Depends(get_db)):
    if pay_crud.get_pay_by_id(db, pay_id):
        try:
            current_filename = pay_crud.get_pay_img_by_id(db, pay_id)
            os.remove(ImgPath + current_filename)
        except FileExistsError:
            log.warning(f'删除图片:{current_filename}失败，未在本地找到相关图片')
        finally:
            if not pay_crud.delete_pay(db, pay_id):
                return Response200(msg='删除打赏图成功')
            return Response500(msg='删除打赏图失败')
    return Response404(msg='打赏图不存在，请重新输入')


@su.post('/picture', summary='新增图床图片', response_model=Union[Response200, Response500])
async def create_picture(post: str, file: UploadFile = File(...), db: Session = Depends(get_db)):
    pic = picture_crud.get_img(db)
    if pic:
        title = picture_crud.get_img_by_title(db, post)
        if not title:
            f = await file.read()
            if 'image' not in file.content_type:
                raise HTTPException(status_code=403, detail='图片格式错误，请重新选择图片')
            filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S.%f')) + '_' + file.filename
            with open(ImgPath + f'{filename}', 'wb') as ff:
                ff.write(f)
            picture_crud.create_img(db, post, filename)
            return Response200(msg='新增图床图片成功', data={'title': post, 'image': filename})
        return Response500(msg='图片标题已存在，请更换title之后重新提交')
    return Response500(mag='新增图床图片失败')


@su.put('/picture/{picture_id}', summary='更新图床图片', response_model=Union[Response200, Response404, Response500])
async def create_picture(picture_id: int, put: str, file: UploadFile = File(...), db: Session = Depends(get_db)):
    if picture_crud.get_img_by_id(db, picture_id):
        if not picture_crud.get_img_by_title(db, put):
            current_filename = picture_crud.get_img_name(db, picture_id)
            try:
                os.remove(ImgPath + current_filename)
            except Exception:
                log.warning(f'删除图片:{current_filename}失败，未在本地找到相关图片')
            finally:
                f = await file.read()
                if 'image' not in file.content_type:
                    raise HTTPException(status_code=403, detail='图片格式错误，请重新选择图片')
                filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S.%f')) + '_' + file.filename
                with open(ImgPath + f'{filename}', 'wb') as ff:
                    ff.write(f)
                if picture_crud.update_img(db, picture_id, filename, put):
                    return Response200(msg='更新图床图片成功', data={'title': put, 'image': filename})
                return Response500(msg='更新图床图片失败')
        return Response500(msg='图片标题已存在，请更换title之后重新提交')
    return Response404(msg='图床图片不存在，请重新输入')


@su.delete('/picture/{picture_id}', summary='删除图床图片', response_model=Union[Response200, Response404, Response500])
async def create_picture(picture_id: int, db: Session = Depends(get_db)):
    if picture_crud.get_img_by_id(db, picture_id):
        current_filename = picture_crud.get_img_name(db, picture_id)
        if current_filename is not None:
            try:
                os.remove(ImgPath + current_filename)
            except Exception:
                log.warning(f'删除图片:{current_filename}失败，未在本地找到相关图片')
        if not picture_crud.delete_img(db, picture_id):
            return Response200(msg='删除图床图片数据成功')
        return Response500(msg='删除图床图片失败')
    return Response404(msg='图床图片不存在，请重新输入')


@su.post('/tag', summary='新增标签', response_model=Union[Response200, Response500])
async def create_tag(post: TagBase, db: Session = Depends(get_db)):
    if tag_crud.get_tag(db):
        if not tag_crud.get_tag_by_name(db, post.tag_name):
            tag_crud.create_tag(db, post)
            return Response200(msg='新增标签成功', data=post)
        return Response500(msg='该标签已存在，不能重复添加')
    return Response500(msg='新增标签失败')


@su.put('/tag/{teg_id}', summary='更新标签', response_model=Union[Response200, Response404, Response500])
async def update_tag(tag_id: int, update: TagBase, db: Session = Depends(get_db)):
    if tag_crud.get_tag_by_id(db, tag_id):
        if not tag_crud.get_tag_by_name(db, update.tag_name):
            if tag_crud.update_tag(db, tag_id, update):
                return Response200(msg='更新标签成功', data=update)
            return Response500(msg='更新标签失败')
        return Response500(msg='标签已存在，请更换标签名重新提交')
    return Response404(msg='标签不存在，请重新输入')


@su.delete('/tag/{teg_id}', summary='删除标签', response_model=Union[Response200, Response404, Response500])
async def delete_tag(tag_id: int, db: Session = Depends(get_db)):
    if tag_crud.get_tag_by_id(db, tag_id):
        if not tag_crud.delete_tag(db, tag_id):
            return Response200(msg='删除标签成功')
        return Response500(msg='删除标签失败')
    return Response404(msg='标签不存在，请重新输入')


@su.post('/conf', summary='新增网站配置')
async def create_conf(website_address: Optional[str] = None,
                      name: Optional[str] = None,
                      chinese_description: Optional[str] = None,
                      english_description: Optional[str] = None,
                      avatar_url: Optional[str] = None,
                      website_author: Optional[str] = None,
                      website_author_url: Optional[str] = None,
                      inbox: Optional[str] = None,
                      website_police: Optional[str] = None,
                      git: Optional[str] = None,
                      file: UploadFile = File(None),
                      db: Session = Depends(get_db)):
    if db.query(func.count(WebConf.id)).scalar() > 0:
        return HTTPException(status_code=403, detail='网站配置已存在，仅能添加一条')
    if inbox is not None:
        try:
            validate_email(inbox)
        except EmailNotValidError:
            raise HTTPException(status_code=403, detail='邮箱输入有误，请重新输入')
    if file is not None:
        f = await file.read()
        if 'image' not in file.content_type:
            raise HTTPException(status_code=403, detail='图片格式错误，请重新选择图片')
        filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S.%f')) + '_' + file.filename
        with open(ImgPath + f'{filename}', 'wb') as ff:
            ff.write(f)
    else:
        filename = None
    conf_obj = WebConf(website_address=website_address,
                       name=name,
                       chinese_description=chinese_description,
                       english_description=english_description,
                       avatar_url=avatar_url,
                       website_author=website_author,
                       website_author_url=website_author_url,
                       inbox=inbox,
                       website_police=website_police,
                       git=git,
                       website_logo=filename)
    db.add(conf_obj)
    db.commit()
    db.refresh(conf_obj)
    return {
        'code': 200,
        'msg': "新增关于信息成功",
        'website_address': website_address,
        'name': name,
        'chinese_description': chinese_description,
        'english_description': english_description,
        'avatar_url': avatar_url,
        'website_author': website_author,
        'website_author_url': website_author_url,
        'inbox': inbox,
        'website_police': website_police,
        'git': git,
        'website_logo': filename
    }


@su.put('/conf', summary='更新网站配置', response_model=Union[Response200, Response404])
async def create_conf(website_address: Optional[str] = None,
                      name: Optional[str] = None,
                      chinese_description: Optional[str] = None,
                      english_description: Optional[str] = None,
                      avatar_url: Optional[str] = None,
                      website_author: Optional[str] = None,
                      website_author_url: Optional[str] = None,
                      inbox: Optional[str] = None,
                      website_police: Optional[str] = None,
                      git: Optional[str] = None,
                      file: UploadFile = File(None),
                      db: Session = Depends(get_db)):
    if db.query(func.count(WebConf.id)).scalar() != 1:
        return Response404(msg='更新网站配置失败，你还没有添加网站配置，添加后才可以进行更新操作')
    if inbox is not None:
        try:
            validate_email(inbox)
        except EmailNotValidError:
            raise HTTPException(status_code=403, detail='邮箱输入有误，请重新输入')
    current_filename = db.query(WebConf).first().website_logo
    if file is not None:
        if current_filename is not None:
            try:
                os.remove(ImgPath + current_filename)
            except Exception:
                log.warning(f'删除图片:{current_filename}失败，未在本地找到相关图片')
        f = await file.read()
        if 'image' not in file.content_type:
            raise HTTPException(status_code=403, detail='图片格式错误，请重新选择图片')
        filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S.%f')) + '_' + file.filename
        with open(ImgPath + f'{filename}', 'wb') as ff:
            ff.write(f)
    else:
        filename = current_filename
    db.query(WebConf).update({
        'website_address': website_address,
        'name': name,
        'chinese_description': chinese_description,
        'english_description': english_description,
        'avatar_url': avatar_url,
        'website_author': website_author,
        'website_author_url': website_author_url,
        'inbox': inbox,
        'website_police': website_police,
        'git': git,
        'website_logo': filename
    })
    db.commit()
    return Response200(
        msg='更新网站配置成功',
        data={'code': 200,
              'msg': "新增关于信息成功",
              'website_address': website_address,
              'name': name,
              'chinese_description': chinese_description,
              'english_description': english_description,
              'avatar_url': avatar_url,
              'website_author': website_author,
              'website_author_url': website_author_url,
              'inbox': inbox,
              'website_police': website_police,
              'git': git,
              'website_logo': filename})


@su.delete('/webconf', summary='删除网站配置', response_model=Union[Response200, Response404])
async def create_webconf(db: Session = Depends(get_db)):
    if db.query(func.count(WebConf.id)).scalar() != 1:
        return Response404(msg='删除网站配置失败，你还没有添加网站配置，添加后才可以进行删除操作')
    current_filename = db.query(WebConf).first().website_logo
    if current_filename is not None:
        try:
            os.remove(ImgPath + current_filename)
        except Exception:
            log.warning(f'删除图片:{current_filename}失败，未在本地找到相关图片')
    db.query(WebConf).delete()
    db.commit()
    return Response200(msg='删除网站配置成功')


@su.delete('/comment/{comment_id}', summary='删除评论', response_model=Union[Response200, Response404, Response500])
async def delete_comment(comment_id: int, db: Session = Depends(get_db)):
    if comment_crud.get_comment_by_id(db, comment_id):
        if not comment_crud.delete_comment(db, comment_id):
            return Response200(msg='删除评论成功')
        return Response500(msg='删除评论失败')
    return Response404(msg='评论不存在，请重新输入')
